from fastapi import Depends, HTTPException, status, Header
from sqlalchemy.ext.asyncio import AsyncSession
from jwt.exceptions import InvalidTokenError


from . import crud
from ..users import crud as user_crud
from ..auth import utils as auth_utils
from scaner.core.models import User, db_helper
from scaner.core.config.log_config import MyLogger


main_logger = MyLogger("main")
logger = main_logger.getChild("bot_api")  # type: ignore


def get_bot_token_payload(token: str) -> dict:
    logger.info("извлечения данных из токена")
    try:
        payload = auth_utils.decode_bot_jwt(token=token)
    except InvalidTokenError as e:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="неверный токен",
        )
    return payload


async def find_user_by_token(
    token: str,
    session: AsyncSession = Depends(db_helper.get_async_session),
) -> User:

    logger.info("Поиск пользователя по токену")
    payload: dict = get_bot_token_payload(token)
    extracted = payload.get("phone")

    if extracted:
        phone: str = extracted
    else:
        phone = ""

    user: User | None = await user_crud.get_user_by_phone(phone=phone, session=session)

    if user:
        return user

    raise HTTPException(
        status_code=status.HTTP_401_UNAUTHORIZED,
        detail="неверный токен",
    )


async def get_user_by_token_depend(
    token: str = Header(alias="X-auth-token"),
    session: AsyncSession = Depends(db_helper.get_async_session),
):
    logger.info("Получение пользователя по токену")
    if user := await crud.get_user_by_token(token=token, session=session):
        return user

    raise HTTPException(
        status_code=status.HTTP_401_UNAUTHORIZED,
        detail="неверный токен",
    )
